package threadlocaldemo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnectionFactory {

    private static final String driverClassName="com.mysql.cj.jdbc.Driver";
    private static final String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false&allowPublicKeyRetrieval=true";
    private static final String username="root";
    private static final String password = "root";
    //构造方法私有
    private DBConnectionFactory(){

    }

    //加载驱动
    static{
        try{
            Class.forName(driverClassName);
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    private static final ThreadLocal<Connection> dbConnectionLocal = new ThreadLocal<Connection>() {
        @Override
        protected Connection initialValue() {
            try {
                return DriverManager.getConnection(url, username, password);
            } catch (SQLException e) {
                e.printStackTrace();
                return null;
            }
        }
    };

    public static Connection getConnection() {
        return dbConnectionLocal.get();
    }

}
